package com.abl.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 程序启动入口
 */
public class Server {

    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(8090);
        System.out.println("服务已启动：8090");
        Socket client = null;
        BufferedReader reader = null;
        PrintWriter writer = null;

        //循环监听
        while (true) {
            try {
                client = server.accept();
                client.setSoTimeout(500);
                reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                writer = new PrintWriter(client.getOutputStream());

                //
                try {
                    String temp;
                    while ((temp = reader.readLine()) != null) {
                        System.out.println(temp);
                    }
                } catch (Exception e) {
                }
                System.out.println("~~~信息接收完毕~~~");

                //获取输出流，拼接返回信息
                //返回请求信息
                StringBuilder responseStr = new StringBuilder();
                responseStr.append("HTTP/1.1 200 OK\n");//响应行
                //响应头+换行
                responseStr.append("content-type:text/html;charset=utf-8\n\n");
                //响应体
                responseStr.append("<html>");
                responseStr.append("<title>Abl Tomcat</title>");
                responseStr.append("<h1> Hello </h1>");
                responseStr.append("</html>");
                writer.print(responseStr);
                writer.flush();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (reader != null) {
                    try {
                        reader.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (client != null) {
                    try {
                        client.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }


    }

}
